﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SharePhone.Provider;

namespace SharePhone.Common.Web
{
    public delegate void SPWebLoadCompleted(object sender, SPWebLoadCompletedEventArgs e);

    public class SPWebCollection : ObservableCollection<SPWeb>
    {
        public DateTime LastRefreshTimeStamp;
        internal ContextSettings Settings;
        internal string WebUrl;

        public SPWebCollection(string webUrl, ContextSettings settings)
        {
            WebUrl = webUrl;
            Settings = settings;
        }

        public void GetWeb(string url, GetWebCompleted callBack)
        {
            WebProvider.GetWeb(callBack, url, Settings);
        }

        /// <summary>
        /// Forces a asynchronous load of all webs in this collection.
        /// </summary>
        public void LoadAll()
        {
            WebProvider.GetWebCollection(GetWebCollection, WebUrl, Settings);
        }

        #region Eventhandler

        public event SPWebLoadCompleted LoadCompleted;

        private void FireLoadCompleted(List<SPWeb> websLoaded)
        {
            if (LoadCompleted != null)
                LoadCompleted(this, new SPWebLoadCompletedEventArgs {Webs = websLoaded});
        }

        #endregion

        #region Callbacks

        private void GetWebCollection(List<SPWeb> webs)
        {
            foreach (SPWeb web in webs)
            {
                Add(web);
            }
            FireLoadCompleted(webs);
        }

        private void GetWeb(SPWeb web)
        {
            if (Contains(web))
                Remove(web);
            Add(web);
            LastRefreshTimeStamp = DateTime.Now;
            FireLoadCompleted(new List<SPWeb> {web});
        }

        #endregion
    }
}